package models;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.DefaultDocument;
import play.db.jpa.GenericModel;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Transient;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Created by xuyang on 2017/6/13.
 */
@Entity(name = "public.\"TA002\"")
public class TA002 extends BeamModel {

    @Column(name = "\"MSG_ID\"")
    public String msg_id;

    @Column(name = "\"GATEWAY_TIME\"")
    public String gateway_time;

    @Column(name = "\"DATAGRAM_TYPE\"")
    public String datagram_type;

    @Column(name = "\"AIRCRAFT_ID\"")
    public String aircraft_id;

    @Column(name = "\"SPLIT_RESULT\"")
    public String split_result;

    @Transient
    public String getSplitResultFragment(int max) {
        if (split_result.length() > max) {
            return split_result.substring(0, max);
        }

        return split_result;
    }

    @Transient
    public String getPrettySplitResult() throws DocumentException, IOException {

//        String xml = split_result;
        String xml = split_result.replace("&#x1;", "&amp;#x1;")
                .replace("&#x2;", "&amp;#x2;").replace("&#x3;", "&amp;#x3;");
//        String xml = split_result.replace("&#x1;", "\001")
//                .replace("&#x2;", "\002").replace("&#x3;", "\003");

        try {
            org.dom4j.io.SAXReader reader = new SAXReader(DocumentFactory.getInstance());

            Document xmlDoc = reader.read(new StringReader(xml));
            OutputFormat formate = OutputFormat.createPrettyPrint();
            StringWriter out = new StringWriter();
            XMLWriter writer = new XMLWriter(out, formate);
            writer.setEscapeText(false);
            writer.write(xmlDoc);

            return out.toString();
        }
        catch(DocumentException e) {
            e.printStackTrace();

            return xml + "\n\n" + e.getLocalizedMessage();
        }
    }
}
